clear; clc;
%% 加载振动和转速数据
path='C:\Users\ADAM\Desktop\data\bearing_outer\increasing20_30\';  
for i=1:3
    all{i}=csvread([path,num2str(i),'.csv'],5,0);
end
speedtemp=[];
speed=[]; 
vibrationtemp1=[];
vibration1=[];
vibrationtemp2=[];
vibration2=[];
for j=1:3
    speedtemp=all{1,j}(:,7);
    speed=[speed;speedtemp];
    vibrationtemp1=all{1,j}(:,1);
    vibration1=[vibration1;vibrationtemp1];
    vibrationtemp2=all{1,j}(:,2);
    vibration2=[vibration2;vibrationtemp2];
end

fs=51200;
time=1/fs:1/fs:30;
figure(1)
plot(time,speed')
title('speed')

figure(2)
plot(time,vibration1')
title('vibration1')

figure(3)
plot(time,vibration2')
title('vibration2')
%% 计算转速
% speed=speed(1024001:2048000,1); %取10秒的数据

LL=0.05;  %反光条长5cm
L1=0.2;   %轮子周长

threshold=20000;              %设置阈值用于调整波形
data_len=length(speed);
speed(speed>threshold)=24000; %将大于阈值的数置为一样的，方便后面查找
speed(speed<threshold)=0;

count=0;                      %计算旋转圈数
for i=1:length(speed)-1
    if(speed(i,1)<speed(i+1,1))
        count=count+1;
    end   
end

jump=zeros(count,1);down=zeros(count,1);
j=1;k=1;

for i=1:length(speed)-1
    if(speed(i,1)<speed(i+1,1))
        jump(j,1)=(i+1)/fs;
        j=j+1;
    end
    
    if(speed(i,1)>speed(i+1,1))
        down(k,1)=i/fs;
        k=k+1;
    end   
end

real_speed=zeros(count-1,1);
t=zeros(count-1,1);
for i=1:count-1
    real_speed(i,1)=1/(jump(i+1,1)-jump(i,1));
    t(i,1)=(jump(i+1,1)+jump(i,1))/2;
end


figure(4)
plot(t,real_speed);
ylabel('ROTATIONAL FREQUENCY')
xlabel('TIME (SECONDS)')
% ii=1;
% ss=zeros(247,1);
% for i=1:247
%     ss(i,1)=(real_speed(ii,1)+real_speed(ii+1,1)+real_speed(ii+2,1))/3;
%     ii=ii+3;
% end